package code.stack;

import java.util.LinkedList;
import java.util.Queue;

// 用队列实现栈
public class StackBasedOnQueue {
    private Queue<Integer> queue;
    private Queue<Integer> tempQueue;

    public StackBasedOnQueue() {
        this.queue = new LinkedList<>();
        this.tempQueue = new LinkedList<>();
    }

    public boolean isEmpty() {
        return queue.isEmpty();
    }

    public void push(int item) {
        queue.add(item);
    }

    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("Stack is empty");
        }
        while (queue.size() > 1) {
            // 先暂存到临时队里
            tempQueue.add(queue.poll());
        }
        int item = queue.poll();
        // 重置队列
        Queue temp = tempQueue;
        tempQueue = queue;
        queue = temp;
        return item;
    }

    public int peek() {
        if (isEmpty()) {
            throw new RuntimeException("Stack is empty");
        }
        while (queue.size() > 1) {
            // 先暂存到临时队里
            tempQueue.add(queue.poll());
        }
        int item = queue.poll();
        tempQueue.add(item);
        // 重置队列
        Queue temp = tempQueue;
        tempQueue = queue;
        queue = temp;
        return item;
    }

    public static void main(String[] args) {
        StackBasedOnQueue stack = new StackBasedOnQueue();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        stack.push(5);
        System.out.println(stack.peek()); // 5
        stack.pop();
        System.out.println(stack.peek()); // 4
        stack.push(6);
        System.out.println(stack.peek()); // 6
    }
}
